package edu.vt.ece_3574.amber_alert.database;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;

import android.os.AsyncTask;
import android.util.Log;
import edu.vt.ece_3574.amber_alert.accounts.Account;

public class DetermineIfUserExists extends AsyncTask<Void, Void, Boolean> {
	private String accountName;
	
	public DetermineIfUserExists(Account account) {
		this.accountName = account.getName();
	}
	
	public DetermineIfUserExists(String name) {
		this.accountName = name;
	}

	@Override
	protected Boolean doInBackground(Void... params) {
		
		InputStream is = null;
		String result = "";
		
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("name", accountName));

		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(DatabaseHandler.databaseURL + "userExistsOnServer.php");
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost); 
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}
		catch(Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result=sb.toString();
		}
		catch (Exception e) {
			Log.e("log_tag", "Error converting result "+e.toString());
		}
		//parse json data
		try{
			new JSONArray(result);
		}
		catch (JSONException e) {
			if (e.toString().contains("User exists")) {
				return true;
			}
			else if (e.toString().contains("User does not exist")) {
				return false;
			}
			else {
				return false;
			}
		}
		return false;
	}
}
